import time
import logging
from typing import Tuple, Optional
from pathlib import Path
from src.core.excelToWord import ExcelToWordConverter
from src.core.xmindToExcel import XMindToExcelConverter


class ParamsHandler:
    """XMind转Word文档流程控制器"""

    @staticmethod
    def control_handler(
            xmind_path: str,
            excel_path: str,
            word_path: str,
            first_step: Optional[str] = None,
            second_prefix: Optional[str] = None,
            precondition_input: Optional[str] = None,
            test_point_input: Optional[str] = None,
            open_excel: bool = False,
            open_word: bool = False
    ) -> Tuple[bool, str]:
        """
        执行完整转换流程 (XMind → Excel → Word)

        Args:
            xmind_path: 输入XMind文件路径
            excel_path: 中间Excel文件路径
            word_path: 输出Word文件路径
            first_step: 第一步操作描述
            second_prefix: 第二步前缀
            open_excel: 是否自动打开Excel
            open_word: 是否自动打开Word

        Returns:
            (成功状态, 描述信息)
        """
        # 前置验证
        if not Path(xmind_path).exists():
            return (False, f"XMind文件不存在: {xmind_path}")

        try:
            start_time = time.time()
            # 第一阶段：XMind转Excel
            logging.info("开始XMind转Excel转换")
            excel_result,message_excel = XMindToExcelConverter.convert(
                xmind_path, excel_path,
                first_step, second_prefix, precondition_input,test_point_input,
                open_excel
            )

            if not excel_result:
                return (False, message_excel)

            # 缓冲等待确保文件写入完成
            time.sleep(1)

            # 第二阶段：Excel转Word
            logging.info("开始Excel转Word转换")
            word_result,message_word = ExcelToWordConverter.convert(
                excel_path, word_path, open_word
            )
            if not word_result:
                return (False, message_word)

            return (True, message_word + message_excel + f"耗时{time.time() - start_time:.2f}秒")

        except Exception as e:
            error_msg = f"转换流程异常: {str(e)}"
            logging.error(error_msg)
            return (False, error_msg)
